package com.topvision.service.api.impl.glass;

import com.topvision.constants.AppConstants;
import com.topvision.constants.TopVisionWebConstants;
import com.topvision.mapper.glass.EquipmentMapper;
import com.topvision.mapper.glass.SysuploadMapper;
import com.topvision.mapper.hes.VideostreamMapper;
import com.topvision.model.glass.Equipment;
import com.topvision.model.glass.Sysupload;
import com.topvision.model.hes.Videostream;
import com.topvision.service.api.glass.AppVideoStreamService;
import com.topvision.util.AppUtil;
import com.topvision.util.R;
import com.topvision.util.ftp.FtpTool;
import com.topvision.util.ftp.SFTPUpload;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service("appVideoStreamService")
public class AppVideoStreamServiceImpl implements AppVideoStreamService {

    @Autowired
    EquipmentMapper equipmentMapper;
    @Autowired
    SysuploadMapper sysuploadMapper;
    @Autowired
    VideostreamMapper videostreamMapper;


    /**
     * Log日志和拍照功能
     *
     * @param request 请求
     * @param files   文件内容
     * @param guid    设备唯一标识
     * @return 保存后文件路径
     */
    @Override
    public R uploadFile(HttpServletRequest request, MultipartFile[] files, String guid) {
        // 通过GUID获取用户信息
        Map<String, Object> map = new HashMap<>();
        map.put("guid", guid);
        map.put("isdeleted", TopVisionWebConstants.DELETED_INT_ZERO);
        Equipment equipment = equipmentMapper.queryObjectByMap(map);
        int pre = (int) System.currentTimeMillis();
        String urls = "";
        // 判断file数组不能为空并且长度大于0
        if (files != null && files.length > 0) {
            // 循环获取file数组中得文件
            for (int i = 0; i < files.length; i++) {
                MultipartFile file = files[i];
                Sysupload entity = new Sysupload();
                // 保存文件
                String fileName = file.getOriginalFilename();
                System.out.println(fileName);
                if (!StringUtils.isEmpty(fileName)) {
                    //创建总目录
                    AppUtil.createFolder(AppConstants.VIDEOSTREAM_PATH);
                    // 固定的备份目录+当前备份者guid 组成目录
                    String folderPath = AppConstants.VIDEOSTREAM_PATH + guid;
                    // 这个字段是用来客户端访问该文件的地址
                    String fileServerPath = TopVisionWebConstants.SERVER_DIR_VIDEOSTREAM_PATH + guid;
                    // 后缀
                    String fileExt = fileName.substring(fileName.lastIndexOf("."));
                    if (AppUtil.isTxt(fileExt)) {
                        folderPath = folderPath + "/" + AppConstants.STR_LOGS;
                        fileServerPath = fileServerPath + "/" + AppConstants.STR_LOGS;
                    } else if (AppUtil.isPhoto(fileExt)) {
                        folderPath = folderPath + "/" + AppConstants.STR_PHOTO;
                        fileServerPath = fileServerPath + "/" + AppConstants.STR_PHOTO;
                    } else if (AppUtil.isVideo(fileExt)) {
                        folderPath = folderPath + "/" + AppConstants.STR_VIDEO;
                        fileServerPath = fileServerPath + "/" + AppConstants.STR_VIDEO;
                    }

                    File folder = AppUtil.createFolder(folderPath);
                    File localFile = new File(folder, fileName);
                    fileServerPath = fileServerPath + "/" + fileName;
                    Map<String, Object> sysUploadMap = new HashMap<>();
                    sysUploadMap.put("filefullpath", fileServerPath);
                    // 判断数据库中是否已存在,如果存在,则不需要在进行备份
                    Sysupload sysupload = sysuploadMapper.queryObjectByMap(sysUploadMap);
                    if (sysupload != null) {
                        // 保存到相应文件
                        try {
                            SFTPUpload.upload(file.getInputStream(), folderPath + "/" + fileName,
                                    folderPath);
                        } catch (Exception e1) {
                            e1.printStackTrace();
                        }
                        continue;
                    }

                    // 客户端请求的ip地址
                    String clientName = request.getRemoteAddr();
                    // 设置服务器ip
                    String serverName = request.getServletPath();
                    entity.setClientname(clientName);
                    entity.setServername(serverName);
                    entity.setFilefullpath(fileServerPath);
                    entity.setFileext(fileExt);
                    entity.setModuleid(AppConstants.MODULE_VIDEOSTREAM);
                    entity.setGuid(guid);
                    entity.setFilesize(Integer.parseInt((file.getSize() + "")));
                    entity.setUuid(UUID.randomUUID().toString().replaceAll("-", ""));
                    entity.setIsdeleted(TopVisionWebConstants.DELETED_FALSE);
                    // 保存所属公司为的是后面通过公司id查询其下面所有上传的文件内容
                    if (equipment != null) {
                        entity.setCompanyId(equipment.getCompanyid());
                    }
                    // 再一次的判断是为了获取相应类型的一些信息保存
                    if (AppUtil.isPhoto(fileExt)) {
                        // 获取上传图片的宽高
                        BufferedImage bi;
                        try {
                            bi = ImageIO.read(file.getInputStream());
                            entity.setFilewidth(bi.getWidth());
                            entity.setFileheight(bi.getHeight());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        sysuploadMapper.save(entity);
                        // 保存到相应文件
                        try {
                            SFTPUpload.upload(file.getInputStream(), folderPath + "/" + fileName,
                                    folderPath);
                        } catch (Exception e1) {
                            e1.printStackTrace();
                        }
                    } else {
                        try {
                            SFTPUpload.upload(file.getInputStream(), folderPath + "/" + fileName,
                                    folderPath);
                        } catch (Exception e1) {
                            e1.printStackTrace();
                        }
                        sysuploadMapper.save(entity);

                    }
                }
                if (StringUtils.isEmpty(urls)) {
                    urls = entity.getFilefullpath();
                    ;
                } else {
                    urls = urls + "," + entity.getFilefullpath();
                    ;
                }
            }
        }
        int finaltime = (int) System.currentTimeMillis();
        System.out.println("备份所用时间:" + (finaltime - pre));
        return R.success(urls);
    }

    @Override
    public Videostream findByCallFlowId(String callFlowId) {
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("callflowid", callFlowId);
        return videostreamMapper.queryObjectByMap(queryMap);
    }

    @Override
    public void saveVideoStreamInfo(Videostream videoStream) {
        videostreamMapper.save(videoStream);
        ;
    }

    @Override
    public int updateVideoStreamInfo(Videostream entity) {
        return videostreamMapper.update(entity);
    }

}
